<template>
  <base-page-view class-name="tab-container home-container" @toTop="clickToTop">
    <!-- 自定义头部 -->
    <base-nav :nav-holder="navHolder" :background="navBackground">
      <view slot="title" class="nav-block">
        <view class="icon-box" :class="{'light':isLight}" @click="$navigateTo('/pagesActivity/sign-page/index')">
          <view class="img-box">
            <url-image width="30" height="30" mode="widthFix" src="/static/images/home/sign-in.gif" />
          </view>
          <view>签到</view>
        </view>
        <view class="icon-box" :class="{'light':isLight}" @click="$navigateTo('/pages/cart/index')">
          <view class="img-box">
            <url-image v-if="isLight" width="30" height="24" mode="widthFix" src="/static/images/home/light-cart.png" />
            <url-image v-else width="30" height="24" mode="widthFix" src="/static/images/home/home-cart.png" />
          </view>
          <text class="num" v-if="cartNums">{{cartNums > 99 ? '99+' : cartNums}}</text>
          <view>购物车</view>
        </view>
        <view class="search-block" @click="toSearch">
          <search-bar :is-light="isLight" background="#F5F5F5" :placeholder="searchHolder" border-radius="2rpx" text-align="left" disabled></search-bar>
        </view>
      </view>
    </base-nav>

    <!-- banner模块 -->
    <view v-if="bannerList.length" class="banner-block">
      <base-swiper :autoplay="false" :is-home="true" mode="aspectFill" :merge-dots="{bottom: 40}" :style-obj="'height:'+bannerHeight+'px'" :swiper-list="bannerList" border-radius="0rpx" @itemClick="bannerClick"></base-swiper>
    </view>

    <!-- menu模块 -->
    <view v-if="menuList.length" class="block menu-block" :class="{bg: !!menuBg, noBanner: bannerList.length===0 }" 
      :style="'background-image:url('+menuBg+')'">
      <swiper class="swiper-menu"
       :indicator-dots="false" circular
       :current="current"
       :interval="5000"
       @change="changeMenu"
       v-if="menuList.length > 8"
       >
        <swiper-item v-for="(menuList, index) in viewMenuList" :key="index">
          <view v-for="item in menuList" :key="item.functionId" class="menu-item" 
            :style="{width: '25%'}" 
            @click="menuClick(item)">
            <!-- :style="{width: menuList.length < 4? (100/menuList.length)+'%' : ''}"  -->
            <b-image :src="item.icon" mode="aspectFit" />
            <view class="menu-text" :style="{color: item.color || (menuBg? '#FFF' : '')}">{{ item.name }}</view>
          </view>
        </swiper-item>
      </swiper>
      <view class="uni-swiper__new-dots-box" v-if="menuList.length > 8">
        <view
          v-for="(item,index) in viewMenuList"
          :key="index"
          :class="[index === current&&'active']"
          class="uni-swiper__dots-item" />
      </view>
      <view v-if="menuList.length <= 8">
        <view v-for="item in menuList" :key="item.functionId" class="menu-item" 
          :style="{width: menuList.length < 4? (100/menuList.length)+'%' : ''}" 
          @click="menuClick(item)">
          <b-image :src="item.icon" mode="aspectFit" />
          <view :style="{color: item.color || (menuBg? '#FFF' : '')}">{{ item.name }}</view>
        </view>
      </view>
    </view>

    <!-- 首页广告通栏 -->
    <!-- <view v-if="advertListOne.length" class="advertise-block">
      <b-image v-for="(item, index) in advertListOne" :key="index" class-name="advertise-item" :src="item.pic" mode="widthFix" @click="advertiseClick(item)" />
    </view> -->
    <view v-if="advertListOne.length" class="advertList-box">
      <view v-for="(item, index) in advertListOne" :key="index" class="advertList">
        <template v-if="!item.adMutiLinkList||item.adMutiLinkList.length<=0">
          <b-image :src="item.pic" mode="widthFix" class="img" @click="advertiseClick(item)"/>
        </template>
        <template v-else>
          <image v-for="(a, b) in item.adMutiLinkList" :key="b" :style="'width:'+item.first_width+'px;height:'+item.first_height+'px;'"
          class="img-box" 
          :src="a.pic" mode="aspectFill" @click="advertiseClick(a)" is_px wh_100/>
        </template>
      </view>
    </view>
    
    <!-- 公告模块 -->
    <view v-if="noticeList.length" class="block notice-block">
      <swiper class="notice-swiper" :autoplay="noticeList.length > 1" :vertical="true" :circular="true">
        <swiper-item v-for="(item,index) in noticeList" :key="index" class="notice-item" @click="noticeItemClick(item)">
          <view class="title">公告</view>
          <view class="content">{{ item.title }}</view>
          <view class="btn">详情</view>
          <image src="/static/images/icon/icon_arror_right_grey.png" mode="aspectFit" />
        </swiper-item>
      </swiper>
    </view>

    <!-- 碧选品牌 -->
    <view v-if="advertListBrandSudoku.length" class="block brand-block">
      <view class="title-part" :class="{hasBanner: !!advertListBrandBanner.length}">
        <view class="title">碧选品牌</view>
        <view v-if="advertListBrandBanner.length" class="banner">
          <base-swiper :autoplay="false" :is-home="true" mode="aspectFill" :style-obj="'height:'+brandBannerHeight+'px;padding: 0 20rpx'" :swiper-list="advertListBrandBanner" border-radius="0rpx" @itemClick="brandBannerClick"></base-swiper>
        </view>
      </view>
      <view class="brand-list">
        <view v-for="(bItem, bIndex) in advertListBrandSudoku" :key="bIndex" class="brand-item" :style="'height:'+brandItemHeight+'px'" @click="brandClick(bItem)">
          <b-image class-name="image" :src="bItem.pic" mode="aspectFill" />
        </view>
      </view>
    </view>

    <!-- 种草、风云人物 -->
    <!-- <view v-if="zhongCaoRecommendList.length || directSalesRankingDTOS.length" class="block material-sales-rank-block">
      <view class="title">
        <view class="sub-item">
          <view v-if="zhongCaoRecommendList.length" class="title-item" :class="{active: blockTab==='zhongCaoRecommendList'}" @click="blockTab='zhongCaoRecommendList'">种草推荐</view>
          <view v-if="directSalesRankingDTOS.length" class="title-item" :class="{active: blockTab==='directSalesRankingDTOS'}" @click="blockTab='directSalesRankingDTOS'">风云人物</view>
        </view>
        <view @click="toViewMore">更多</view>
        <image src="/static/images/icon/icon_arror_right_grey.png" mode="aspecFit" @click="toViewMore" />
      </view>
      <view class="content">
        <template v-if="blockTab==='zhongCaoRecommendList'">
          <view v-for="(item, index) in zhongCaoRecommendList" :key="index" class="rank-item" @click="toMartialDetail(item)">
            <b-image :src="item.cover || 'https://asset.bisinuolan.cn/bixuan_uni/images/mine/touxiang.png'" class-name="photo" mode="aspectFill" @error="onImageLoad(item)" />
            <view class="right-part">
              <view class="label">上榜推荐</view>
              <view class="slogan">{{ item.title }}</view>
              <view style="margin-top: 20rpx;">{{ (item.shareNum || item.share_num) | formatNumber(2, true) }}人种草</view>
            </view>
            <image class="icon" src="/static/images/icon/icon_view.png" mode="aspectFit" />
          </view>
        </template>
        <template v-else-if="blockTab==='directSalesRankingDTOS'">
          <view v-for="(item, index) in directSalesRankingDTOS" :key="index" class="rank-item" @click="toTopRankDetail(item)">
            <b-image :src="item.imagePhotoUrl || 'https://asset.bisinuolan.cn/bixuan_uni/images/mine/touxiang.png'" class-name="photo" mode="aspectFill" @error="onImageLoad(item)" />
            <view class="right-part">
              <view class="label">{{ ['冠军技巧','亚军技巧','季军技巧'][index] }}</view>
              <view class="slogan">{{ item.slogan || '主人太懒了，还没来得及写心得口号～' }}</view>
              <view style="margin-top: 20rpx;">销售业绩：<text class="volume">{{ item.salesVolume }}</text></view>
            </view>
            <image class="icon" src="/static/images/icon/icon_view.png" mode="aspectFit" />
          </view>
        </template>
      </view>
    </view> -->

    <!-- 首页底部通栏广告 -->
    <view v-if="rollBannerList.length" class="block roll-banner-block">
      <base-swiper :is-home="true" mode="aspectFill" :style-obj="'height:'+rollBannerHeight+'px'" :swiper-list="rollBannerList" border-radius="0rpx" @itemClick="rollBannerClick"></base-swiper>
    </view>

    <!-- 分类推荐 -->
    <template v-if="cateRecommendList.length">
      <view class="sticky-wrapper" :class="{hasSubTitle: hasSubTitle}" :style="'top: '+(systemInfo.statusBarHeight+44)+'px'">
        <horizontal-list list-name="cate-recommend" :list="cateRecommendList" :other-params="{hasSubTitle}" @itemClick="cateRecommendClick">
          <template v-slot="{item, otherParams}">
            <view class="title" :class="{noSubTitle: !item.subtitle}">{{ item.title }}</view>
            <view v-if="otherParams.hasSubTitle" class="sub-title" :class="{disabled: !item.subtitle}">{{ item.subtitle || '-' }}</view>
          </template>
        </horizontal-list>
      </view>
      <waterFall ref="waterFall" :list="cateRecommendGoodsList" :min-height="minHeight">
        <template v-slot="{ item, columnIndex, index }">
          <view class="goods-item" :class="{mini: columnIndex === 1 && index===0}" @click="goodsClick(item)">
            <view class="bg">
              <b-image class-name="item-image" :src="item.pic" mode="aspectFill" />
              <view class="content">
                <view class="item-name">{{ item.title }}</view>
                <!-- <view v-if="item.commission_result" class="item-commission">{{ item.commission_result }}</view> -->
                <view v-if="item.diamond_price" class="item-commission">钻石价 ￥{{ item.diamond_price }}</view>
                <view class="item-footer">
                  <view class="price">{{ item.price }}</view>
                  <view v-if="item.volume" class="sale">已售{{ item.volume }}件</view>
                </view>
              </view>
            </view>
          </view>
        </template>
        <template slot="footer">
          <base-list-state :list-length="listLength" :list-query="goodsQuery" :list-state="goodsState" :list-empty="listEmpty" @btnClick="emptyBtnClick" />
        </template>
      </waterFall>
    </template>

    <!-- 首页弹窗 -->
    <view v-if="home_pop.pic" class="home-pop" @touchmove.stop="()=>{}">
      <view class="pop-content">
        <image :src="home_pop.pic" class="pop-img" mode="aspectFit" @click="popClick" />
        <image class="close-btn" src="/static/images/order/icon_cancel.png" mode="aspectFit" @click="closePop" />
      </view>
    </view>

    <!-- 新用户专享 -->
    <view v-if="new_member_pro.length && showNewPer" class="block advertise-block new-member-block">
      <view v-for="(item, index) in new_member_pro" :key="index" @click="newMemberClick(item, 'active')">
        <b-image :src="item.pic" mode="widthFix" />
        <view class="new-close-icon" @click.stop.prevent="showNewPer=false">
          <image src="/static/images/home/new_p_c.png" />
        </view>
      </view>
    </view>

    <!-- 热分享滚动列表 -->
    <swiper v-if="hotShareList.length && scrollTop < 1000" class="hot-share-list" :style="{top: systemInfo.statusBarHeight+44+20+'px', marginTop: hotShareMarginTop}" :autoplay="true" :interval="3000" vertical circular>
      <swiper-item v-for="(item, index) in hotShareList" :key="index">
        <view class="swiper-item">
          <image :src="item.userHeadImageUrl||'/static/images/mine/touxiang.png'" mode="aspectFill" />
          <view class="sub-item" :style="'background-image: url('+bgHotShare+')'">{{ item.userName }}分享{{ item.commodityName }}</view>
        </view>
      </swiper-item>
    </swiper>

    <!-- 红包雨活动弹窗 -->
    <view v-if="packetDataPic && showRedPic" class="home-pop red-packet">
      <b-image :src="packetDataPic" mode="widthFix" width="600" height="804" @click="handleRedClick" />
      <image class="close-btn-red" src="/static/images/order/icon_cancel.png" mode="aspectFit" @click.stop.prevent="showRedPic=false" />
    </view>

    <!-- 分享模块 -->
    <view class="share-icon" :class="{ active: showShareIcon }" @click="showSharePop">
      <image src="/static/images/icon/icon_share_circle.png" mode="aspectFit" />
    </view>
    <share ref="sharePop" :share-option="shareOption" @btnClick="shareBtnClick" />
  </base-page-view>
</template>

<script>
import { h5NavigateTo, toFunctionDetail, toGoods } from '@/utils/navigateTo'
import { arraySplit, debounce, deepClone } from '@/utils/tools'
import searchBar from '@/components/searchBar/index'
import baseSwiper from '@/components/base/base-swiper.vue'
import horizontalList from '@/components/horizontalList/index'
import waterFall from '@/components/waterFall/index'
import baseListState from '@/components/base/base-list-state'
import share from '@/components/draw/share'
import './index.scss'

export default {
  components: {
    searchBar,
    baseSwiper,
    horizontalList,
    waterFall,
    baseListState,
    share
  },
  data() {
    return {
      // 全局
      pageLoaded: false,
      scrollTop: 0,
      heightForNavBgTransform: 44,
      navHolder: false,
      isLight: true,
      navBackground: 'rgba(255, 255, 255, 0)',

      // 搜索模块
      searchHolder: '请输入要搜索商品', // '周年庆返场活动最高减800'

      // banner模块
      bannerList: [],
      bannerHeight: '', // 轮播图的高度

      // menu模块
      menuBg: '',
      menuList: [],

      // 首页广告通栏模块
      advertListOne: [],
      firstLoadAdvert:true,//第一次加载
      // 公告模块
      noticeList: [],

      // 碧选品牌
      advertListBrandBanner: [],
      advertListBrandSudoku: [],//九宫格图片
      brandBannerHeight: '', // 品牌轮播图的高度
      brandItemHeight: '', // 品牌item的高度
      brandListHeight: '', // 品牌list的高度

      // 种草、风云人物
      blockTab: '',
      zhongCaoRecommendList: [],
      directSalesRankingDTOS: [],

      // 首页滚动轮播广告
      rollBannerList: [],
      rollBannerHeight: '', // 首页滚动轮播图的高度

      // 分类推荐模块
      cateRecommendList: [],
      hasSubTitle: false,
      goodsQuery: {
        id: '',
        pageIndex: 1,
        pageSize: 10
      },
      goodsState: {
        loading: false,
        more: true
      },
      cateRecommendGoodsList: [],
      goodsListLength: 0,
      needRefreshGoodsList: false,
      listEmpty: {
        type: 'empty_commodity',
        text: '暂无商品',
        btnText: '刷新'
      },
      minHeight: 0,

      // 首页弹窗
      home_pop: {
        pic: ''
      },

      // 新用户专享
      showNewPer: true,
      new_member_pro: [],
      toNewMember: false,

      // 热分享滚动
      hotShareMarginTop: 0,
      hotShareList: [],
      bgHotShare: Object.freeze(`${process.env.VUE_APP_IMAGE_ASSET}/images/home/bg_hot_share.png`),

      // 红包雨活动
      packetDataPic: '',
      showRedPic: false, // 是否显示红包

      // 分享模块
      showShareIcon: true,
      shareTimer: null,
      shareBg: `${process.env.VUE_APP_IMAGE_ASSET}/images/share/`,
      shareOption: {} ,// 分享自定义设置
      cartNums:0,//购物车数量
      current: 0, // 当前菜单的滚动下标
    }
  },
  computed: {
    listLength() { // 由于微信小程序无法自动更新base-list-state组件,故采用computed
      return this.cateRecommendGoodsList.length
    },
    // 新的菜单
    viewMenuList() {
      let arr = arraySplit(this.menuList, 8)
      return arr
    }
  },
  created() {},
  onLoad() {
    this.fetchData()
    this.initHomePop()
    this.fetchHotShareData()
    uni.$on('login', () => {
      this.needRefreshGoodsList = true
    })
  },
  onShow() {
    if (this.pageLoaded) {
      this.fetchData(true)

      if (this.needRefreshGoodsList && this.goodsListLength) {
        this.getRecommendGoods({
          ...this.goodsQuery,
          pageIndex: 1,
          pageSize: this.goodsListLength
        })
      }
      this.needRefreshGoodsList = false

      this.checkNewMember(this.toNewMember)
      this.toNewMember = false
    } else {
      this.checkNewMember()
    }
    this.redPacketData();
    this.getCartNums();
  },
  onShareAppMessage(res) {
    // return this.$queryShareOption(res, this.shareOption)
  },
  onPullDownRefresh() {
    this.fetchData(true)
    this.fetchHotShareData();
    this.getCartNums();
  },
  onReachBottom: debounce(function() {
    if (this.goodsQuery.id && this.goodsState.more && !this.goodsState.loading) {
      this.goodsQuery.pageIndex++
      this.getRecommendGoods()
    }
  }, 500),
  onHide() {
    if (this.timerRed) {
      clearInterval(this.timerRed)
    }
  },
  onPageScroll(res) {
    this.scrollTop = res.scrollTop

    // 导航栏渐变效果
    if (this.heightForNavBgTransform) {
      const opacity = this.scrollTop / this.heightForNavBgTransform > 1 ? 1 : this.scrollTop / 44
      this.navBackground = `rgba(255, 255, 255, ${opacity})`
      this.isLight = opacity < 1
      uni.setNavigationBarColor({
        frontColor: this.isLight ? '#ffffff' : '#000000',
        backgroundColor: '#ffffff'
      })
    }

    if (this.scrollTop > 300 && this.cateRecommendGoodsList.length === 0 && this.goodsQuery.pageIndex === 1 && this.goodsState.more && !this.goodsState.loading) {
      this.getRecommendGoods()
    }

    // 分享按钮显示效果
    this.showShareIcon = false
    clearInterval(this.shareTimer)
    this.shareTimer = setTimeout(() => {
      this.showShareIcon = true
    }, 500)
  },
  methods: {
    changeMenu(ev){
      console.log(ev)
      this.current = ev.detail.current
    },
    //获取购物车数量
    async getCartNums() {
      if (!this.userInfo || !this.userInfo.uid ) {
        return false
      }
      const res = await this.$api.cartApi.getCartNums({})
      if (res.code) {
        return
      }
      this.cartNums = res.data
    },
    // 获取首页数据
    async fetchData(isRefresh) {
      const res = await this.$api.homeApi.getHomeDetail({
        hideLoading: !!isRefresh
      })
      if (res.success && res.data) {
        const { bannerList } = res.data
        const hasBanner = !!(bannerList && bannerList.length)
        this.heightForNavBgTransform = hasBanner ? 44 : 0
        this.navHolder = !hasBanner
        this.isLight = hasBanner
        this.navBackground = hasBanner ? 'rgba(255, 255, 255, 0)' : 'rgba(255, 255, 255, 1)'
        this.hotShareMarginTop = hasBanner ? 0 : '64rpx'
        uni.setNavigationBarColor({
          frontColor: hasBanner ? '#ffffff' : '#000000',
          backgroundColor: '#ffffff'
        })
        if (bannerList && bannerList.length) {
          uni.getImageInfo({
            src: bannerList[0].pic,
            success: (res) => {
              const picHeight = this.systemInfo.screenWidth * res.height / res.width
              this.bannerHeight = picHeight
            },
            complete: () => {
              this.initHomeData(res.data, isRefresh)
            }
          })
        } else {
          this.initHomeData(res.data, isRefresh)
        }
      }
      this.pageLoaded = true
      uni.stopPullDownRefresh()
    },
    getImgInfo(src){
      return new Promise((resolve, reject) => {
        uni.getImageInfo({
          src: src,
          success: (res) => {
            resolve(res);
          },
          fail: (err) => {
            reject(err);
          },
        })
      });
    },
    // 初始化首页数据
    async initHomeData(homeData, isRefresh) {
      const { bannerList, functionBackground, menuList, advertListOne, noticeList, advertListBrandBanner, advertListBrandSudoku, zhongCaoRecommendList, directSalesRankingDTOS, rollBannerList, cateRecommendList, homeJump } = homeData
      
      this.bannerList = Object.freeze(bannerList || [])
      this.menuBg = functionBackground || ''
      this.menuList = Object.freeze(menuList || []);
      if(this.firstLoadAdvert){
        this.advertListOne = advertListOne || [];
        this.firstLoadAdvert=false;
      }
      for (let s of advertListOne) {
        if(s.adMutiLinkList&&s.adMutiLinkList.length>0){
          let res=await this.getImgInfo(s.adMutiLinkList[0].pic);
          this.$set(s,'first_height',this.systemInfo.screenWidth/s.adMutiLinkList.length * res.height / res.width);
          this.$set(s,'first_width',this.systemInfo.screenWidth/s.adMutiLinkList.length);
        }
      }
      this.advertListOne = advertListOne || [];
      console.log(this.advertListOne)
      
      this.noticeList = noticeList || []
      if (homeJump) {
        this.initHomeJump(homeJump, isRefresh)
      }
      if (advertListBrandBanner && advertListBrandBanner.length) {
        this.getImageShowHeight({
          pic: advertListBrandBanner[0].pic,
          width: this.systemInfo.screenWidth - this.rpxToPx(40),
          key: 'brandBannerHeight'
        }, () => {
          this.advertListBrandBanner = advertListBrandBanner || []
        })
      }
      if (advertListBrandSudoku && advertListBrandSudoku.length) {
        this.getImageShowHeight({
          pic: advertListBrandSudoku[0].pic,
          width: (this.systemInfo.screenWidth - this.rpxToPx(10)) / 3,
          key: 'brandItemHeight',
          isPage: advertListBrandSudoku.length > 9
        }, () => {
          this.advertListBrandSudoku=advertListBrandSudoku;
        })
      }
      if (rollBannerList && rollBannerList.length) {
        this.getImageShowHeight({
          pic: rollBannerList[0].pic,
          width: this.systemInfo.screenWidth,
          key: 'rollBannerHeight'
        }, () => {
          this.rollBannerList = rollBannerList || []
        })
      }

      this.zhongCaoRecommendList = zhongCaoRecommendList || []
      this.directSalesRankingDTOS = directSalesRankingDTOS || []
      if (this.zhongCaoRecommendList.length) {
        this.blockTab = 'zhongCaoRecommendList'
      } else if (this.directSalesRankingDTOS.length) {
        this.blockTab = 'directSalesRankingDTOS'
      }
      this.cateRecommendList = cateRecommendList || []
      // this.cateRecommendGoodsList = []
      // this.goodsListLength = 0
      // this.goodsQuery.pageIndex = 1
      // this.goodsState.more = true
      this.hasSubTitle = this.cateRecommendList.some(i => i.subtitle)
      if (!isRefresh && this.cateRecommendList.length) {
        this.goodsQuery.id = this.cateRecommendList[0].id
      }
    },

    // 获取首页热卖分享列表信息
    async fetchHotShareData() {
      const res = await this.$api.homeApi.getHomeShareList()
      if (res.success && res.data) {
        this.hotShareList = res.data || []
      }
    },

    // 获取首页推荐分类商品
    async getRecommendGoods(query) {
      const goodsQuery = query || this.goodsQuery
      if (!goodsQuery.id) {
        return
      }
      this.goodsState.loading = true
      this.minHeight = this.systemInfo.screenHeight - 167
      const res = await this.$api.homeApi.getHomeRecommendGoods({ ...goodsQuery })
      if (goodsQuery.pageIndex === 1) {
        this.cateRecommendGoodsList = []
        this.goodsListLength = 0
      }
      if (res.success) {
        this.listEmpty.text = '暂无商品'
        const goodsList = (res.data || [])
        goodsList.map(item => {
          item.price = (item.price || 0).toFixed(2)
          item.diamond_price = (item.diamond_price || 0).toFixed(2)
          let volume = ''
          const nVolume = Number(item.volume)
          if (nVolume > 0) {
            volume = nVolume
            if (nVolume > 9999) {
              volume = (Math.floor((nVolume / 1000)) / 10).toFixed(1) + '万'
            }
            if (nVolume > 99999999) {
              volume = (Math.floor((nVolume / 10000000)) / 10).toFixed(1) + '亿'
            }
          }
          item.volume = volume
          let text = ''
          let commission = 0
          if (this.token && this.userInfo.current_member_card_type > 1) {
            text = '返收益¥'
            commission = item[['', '', 'region_commission', 'director_commission'][this.userInfo.current_member_card_type]]
          } else {
            text = '升级VIP省¥'
            commission = item.region_commission
          }
          if (commission > 0) {
            item.commission_result = `${text}${commission.toFixed(2)}`
          }
        })
        this.goodsState.more = goodsList.length === goodsQuery.pageSize

        if (goodsQuery.pageIndex === 1) {
          this.cateRecommendGoodsList = goodsList
          this.goodsListLength = goodsList.length
          this.$nextTick(() => {
            this.$refs.waterFall.init()
          })
        } else if (goodsList.length) {
          this.goodsListLength += goodsList.length
          this.$refs.waterFall.addToList(goodsList)
        }
      } else {
        this.listEmpty.text = res.msg
        this.goodsState.more = false
      }
      this.goodsState.loading = false
    },

    // 初始化固定首页跳转逻辑
    initHomeJump(homeJump, isRefresh) {
      setTimeout(() => {
        if (!isRefresh && homeJump.json) {
          const jumpData = JSON.parse(homeJump.json || '{}')
          switch (jumpData.jumpType) {
            case 'h5':
              h5NavigateTo(jumpData.jumpVal)
              break
            case 'home':
            // var cateIndex = this.navData.findIndex((item) => item.tabId === jumpData.jumpVal)
            // this.handleCategoryClick(cateIndex)
            // setTimeout(() => {
            //   if (this.$refs['category-list']) {
            //     this.$refs['category-list'].setIndex(cateIndex)
            //   }
            // }, 1000)
              break
            case 'vip':
              this.$navigateTo('/pagesMember/vip/index')
              break
            case '直播':
            // toFunctionDetail({ type: 8, type_val: '/pagesDetail/living-list/index' })
              break
            case '攻略':
              this.$navigateTo('/pages/moments/index')
              break
            case '拼团':
              this.$navigateTo('/pagesActivity/group-buy/index')
              break
            case '签到':
              this.$navigateTo('/pagesActivity/sign-page/index')
              break
            case '小秘密':
              break
            case '碧划算':
              this.$navigateTo('/pages/coupon/index', 'switchTab')
              break
            default:
              break
          }
        }
      }, 500)
    },

    // 像素单位转换
    rpxToPx(val) {
      return this.systemInfo.screenWidth / 750 * val
    },
    getImageShowHeight({ pic, width, key, isPage }, complete) {
      uni.getImageInfo({
        src: pic,
        success: (res) => {
          const picHeight = width * res.height / res.width
          this[key] = picHeight
          if (key === 'brandItemHeight') {
            this.brandListHeight = picHeight * 3 + (isPage ? 20 : 0)
          }
        },
        complete
      })
    },

    // 点击搜索栏
    toSearch() {
      this.$trackSDK.track('bx.home.search.click')
      this.$navigateTo('/pagesPublic/search/index')
    },

    handleFunction(item, event_key, collection) {
      this.$trackSDK.track(event_key, item.functionId || item.id, {
        title: item.name || item.title,
        ad_id: item.functionId || item.id
      })
      this.toDetail(item, 'navigateTo', collection)
    },
    toDetail(item, type = 'navigateTo', collection = { preseat: item.title, firstseat: '今日热推' }) {
      console.log(item)
      if (item.jumpType === 1) {
        return
      } else if (item.jumpType === 2) {
        const url = item.type_val ? item.type_val : item.typeVal
        h5NavigateTo(url)
      } else {
        item.type_val = item.type_val ? item.type_val : item.typeVal
        item.from_type = item.from_type ? item.from_type : item.fromType
        item.activity_id = item.activity_id ? item.activity_id : item.activityId
        toFunctionDetail(item, type, collection)
      }
      if (item.jumpType === 1 || item.jumpType === 2) {
        if (collection.preseat) {
          uni.setStorage({
            key: 'preseat',
            data: collection.preseat
          })
        }
        if (collection.firstseat) {
          uni.setStorage({
            key: 'firstseat',
            data: collection.firstseat
          })
        }
      }
    },

    // 点击banner
    bannerClick({ item }) {
      const collection = { preseat: item.title, firstseat: '首页_banner_' + item.title }
      this.handleFunction(item, 'bx.home.carousel.click', collection)
    },

    // 点击menu
    menuClick(item) {
      const collection = { preseat: item.title, firstseat: '首页_运营位_' + item.name }
      this.handleFunction(item, 'bx.home.menu.click', collection)
    },

    // 点击广告通栏
    advertiseClick(item) {
      const collection = { preseat: item.title, firstseat: '首页_中部广告_' + item.title }
      this.handleFunction(item, 'bx.home.banner.click', collection)
    },

    // 公告点击
    noticeItemClick(item) {
      this.$trackSDK.track('bx.home.announcement.click', item.id, {
        title: item.title,
        ad_id: item.id
      })
      uni.setStorageSync('firstseat', '首页_文字轮播_' + item.title)
      if (!item.jumpUrl) return
      h5NavigateTo(item.jumpUrl)
    },

    // 点击品牌banner
    brandBannerClick({ item }) {
      const collection = { preseat: item.title, firstseat: '首页_brand_banner_' + item.title }
      this.handleFunction(item, 'bx.home.brand_ad.click', collection)
    },
    onImageLoad(item) {
      this.$set(item, 'imagePhotoUrl', 'https://asset.bisinuolan.cn/bixuan_uni/images/mine/touxiang.png')
    },
    // 点击品牌
    brandClick(item) {
      const collection = { preseat: item.title, firstseat: '首页_brand_' + item.title }
      this.handleFunction(item, 'bx.home.brand.click', collection)
    },

    // 点击种草、风云人物-更多
    toViewMore() {
      console.log(this.blockTab)
      this.$trackSDK.track('bx.home.button.click', '', {
        title: this.blockTab === 'zhongCaoRecommendList' ? '种草推荐更多' : '风云人物更多'
      })
      if (this.blockTab === 'zhongCaoRecommendList') {
        uni.setStorageSync('firstseat', '首页_种草推荐')
        this.$navigateTo('/pages/moments/index', 'switchTab')
      } else {
        uni.setStorageSync('firstseat', '首页_风云人物')
        this.$navigateTo('/pagesActivity/sale-top-ranking/index')
      }
    },
    // 点击种草，跳种草详情
    toMartialDetail(item) {
      this.$trackSDK.track('bx.home.post.click', item.id, {
        title: '种草列表',
        post_id: item.id,
        post_name: item.title
      })
      this.$navigateTo(`/pagesMaterial/detail/index?id=${item.id}`)
    },
    // 点击风云人物，跳风云人物详情
    toTopRankDetail(item) {
      this.$trackSDK.track('bx.home.people.click', item.userId, {
        title: '人物列表',
        people_id: item.userId,
        people_name: item.userName
      })
      this.$navigateTo(`/pagesActivity/sale-top-ranking/detail?id=${item.userId}`)
    },

    // 点击rollBanner
    rollBannerClick({ item }) {
      const collection = { preseat: item.title, firstseat: '首页_roll_banner_' + item.title }
      this.handleFunction(item, 'bx.home.ab.click', collection)
    },

    // 点击分类推荐
    cateRecommendClick(index) {
      this.goodsQuery.id = this.cateRecommendList[index].id
      this.goodsQuery.pageIndex = 1
      console.log(3)
      this.getRecommendGoods()
      this.$trackSDK.track('bx.home.tab.click', this.goodsQuery.id, {
        title: this.cateRecommendList[index].title,
        ad_id: this.goodsQuery.id
      })
    },

    // 点击分类推荐商品
    goodsClick(item) {
      this.$trackSDK.track('bx.home.sale.click', '', {
        title: '商品列表',
        good_id: item.goods_id,
        good_name: item.title
      })
      toGoods(item)
      // console.log(item, toGoods, 666)
    },
    emptyBtnClick() {
      this.goodsQuery.pageIndex = 1
      this.goodsState.more = true
      console.log(4)
      this.getRecommendGoods()
    },

    // 获取首页popup
    async initHomePop() {
      this.home_pop = { pic: '' }
      const userId = this.userInfo.uid || ''
      const res = await this.$api.commonApi.queryLaunch({ userId: userId })
      if (res.success && res.data) {
        this.home_pop = res.data.home_pop || { pic: '' }
      }
    },
    // 点击首页popup
    popClick() {
      const item = { ... this.home_pop }
      this.home_pop = { pic: '' }
      if (item.title === '未购买38元礼包') {
        this.$trackSDK.track('bx.38_gift.dialog.click', '', {
          title: item.title
        })
      } else {
        this.$trackSDK.track('bx.home.dialog.click', item.id, {
          title: item.title
        })
      }
      toFunctionDetail(item, 'navigateTo', {
        preseat: '弹窗:' + item.title,
        firstseat: '今日热推'
      })
    },
    // 关闭首页popup
    closePop() {
      this.home_pop = { pic: '' }
    },

    // 检查是否是新用户
    async checkNewMember(flag) {
      if (this.token && this.userInfo.uid) {
        const res = await this.$api.excellentApi.isNewUser()
        if (res.success && res.data) {
          this.fetchNewMemberBanner()
        } else {
          this.new_member_pro = []
          if (flag) {
            uni.removeStorage({ key: 'pageAfterLogin' })
            setTimeout(() => {
              uni.showToast({
                title: '您已经是老用户啦',
                icon: 'none'
              })
            }, 500)
          }
        }
      } else {
        this.fetchNewMemberBanner()
      }
    },
    // 获取新用户专享
    async fetchNewMemberBanner() {
      const res = await this.$api.excellentApi.getHomeBanner()
      if (res.success) {
        this.new_member_pro = res.data || []
      }
    },
    // 点击新用户广告
    newMemberClick(item) {
      this.$trackSDK.track('bx.home.new_float.click', item.id, {
        title: item.title
      })

      if (this.token) {
        if (item.jumpType === 2) {
          const url = item.type_val ? item.type_val : item.typeVal
          uni.setStorageSync('firstseat', '首页_底部广告_' + item.title)
          h5NavigateTo(url)
        } else {
          item.type_val = item.type_val ? item.type_val : item.typeVal
          toFunctionDetail(item, '', { preseat: item.title, firstseat: '首页_底部广告_' + item.title })
        }
      } else {
        this.toNewMember = true
        const url = item.type_val ? item.type_val : item.typeVal
        if (url && url.match('bisinuolan.cn')) {
          const page = url.split('bisinuolan.cn')[1]
          uni.setStorage({ key: 'pageAfterLogin', data: {
            pageType: 'newMember',
            page
          }})
        }
        this.$navigateTo('/pages/login/index')
      }
    },

    // 获取红包弹窗数据
    async redPacketData() {
      this.showRedPic = false
      const res = await this.$api.redPacketApi.getActivityApp({}, { showMessage: false, showLoading: false })
      if (res.success && res.data) {
        const data = res.data
        this.packetDataPic = data.red_bag_rain.pic
        this.typeVal = data.red_bag_rain ? data.red_bag_rain.type_val : ''
        // 小于60就弹窗，大于倒计时，只要接口给，小于60都会弹出
        let disSec = data.start_time - data.system_time
        if (disSec > 60) {
          // 启动定时器
          console.log('启动定时器')
          this.timerRed = setInterval(() => {
            disSec--
            if (disSec <= 60) {
              clearInterval(this.timerRed)
              this.showRedPic = true
              console.log('定时器结束，弹窗')
            }
          }, 1000)
          this.$on('hook:deactivated', () => {
            clearInterval(this.timerRed);                                    
          })
        } else if (disSec <= 60 && disSec >= 0) {
          this.showRedPic = true
        }
      }
    },
    // 红包点击
    handleRedClick() {
      if (this.typeVal) {
        clearInterval(this.timerRed)
        h5NavigateTo(this.typeVal)
      }
    },

    // 点击分享按钮
    showSharePop() {
      this.$trackSDK.track('bx.home.button.click', '', {
        title: '分享按钮'
      })
      if (this.token) {
        this.$refs.sharePop.show(this.shareOption)
      } else {
        this.$navigateTo('/pages/login/index')
      }
    },
    shareBtnClick(btnText) {
      this.$trackSDK.track('bx.home.button.click', '', {
        title: btnText
      })
    },

    // 点击回到顶部
    clickToTop() {
      this.$trackSDK.track('bx.home.button.click', '', {
        title: '返回顶部'
      })
    },

    // 分享初始化
    initShare() {
      if (this.token) {
        this.shareOption.share_url = ''
        this.shareOption.share_list = [
          {
            pic: this.shareBg + 'share_01.jpg',
            titleArr: [
              '选择，大于努力',
              '加入碧选',
              '自购分享多赚一点'
              // '自用省钱 分享赚钱',
              // '衣食住行购+直播',
              // '坐享多维管道收益'
            ]
          },
          {
            pic: this.shareBg + 'share_02.jpg',
            titleArr: [
              '选择，大于努力',
              '加入碧选',
              '自购分享多赚一点'
              // '自营爆品 全网尖货',
              // '人人可推 笔笔可赚',
              // '来碧选开启你的省赚外挂'
            ]
          },
          {
            pic: this.shareBg + 'share_03.jpg',
            titleArr: [
              '选择，大于努力',
              '加入碧选',
              '自购分享多赚一点'
              // '38元开启掌上事业',
              // '万亿商机 尽在碧选'
            ]
          }
        ]
        this.showShare()
      } else {
        this.hideShare()
      }
    }
  }
}
</script>
